package com.yueyang.sojourn.server.common.baymax.web.resolver;

import com.yueyang.sojourn.server.common.baymax.web.result.exception.AbstractResultException;
import org.springframework.http.converter.HttpMessageConverter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * 处理 {@link AbstractResultException}异常的子类，将异常转换为标准RestMessage
 * </p>
 * 
 * @see com.yueyang.sojourn.server.common.baymax.web.result.JAssert
 * @author huisman
 * @Copyright (c) 2015, yueyang Group All Rights Reserved.
 */
public class RestResultExceptionResolver
    extends AbstractResultExceptionResolver {

  private final boolean logTrace;

  public RestResultExceptionResolver(boolean logTrace) {
    this.logTrace = logTrace;
  }

  @Override
  public int getOrder() {
    return HIGHEST_PRECEDENCE + 10000000;
  }



  public RestResultExceptionResolver(boolean logTrace,
      List<HttpMessageConverter<?>> additionalMessageConverters) {
    super(additionalMessageConverters);
    this.logTrace = logTrace;
  }



  @Override
  protected void logException(Exception ex, HttpServletRequest request) {
    if (this.logTrace) {
      this.logger.error(formatLogMessage(false, ex, request), ex);
    }
  }

  @Override
  protected boolean shouldResolveException(HttpServletRequest request,
      HttpServletResponse response, Object handler, Exception ex) {
    if (ex == null) {
      return false;
    }
    return RestResponseMessageProviders.support(ex);
  }

  @Override
  protected RestResponseMessage resolveResponseMessage(
      HttpServletRequest request, HttpServletResponse response, Object handler,
      Exception ex) {
    return RestResponseMessageProviders.getRestResponseMessage(ex);
  }

}
